﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Form1.cs" company="VCD">
//   (C) 2010
// </copyright>
// <summary>
//   Defines the Form1 type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Id3stuff
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        private readonly BackgroundWorker bgwFindTracks = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            this.bgwFindTracks.WorkerReportsProgress = true;
            this.bgwFindTracks.DoWork += this.FindTracks;
            this.bgwFindTracks.RunWorkerCompleted += this.BgwFindTracksRunWorkerCompleted;
            this.bgwFindTracks.ProgressChanged += this.BgwFindTracksProgressChanged;    
        }

        private static void PopulateTree(string dir, TreeNode node)
        {
            var directory = new DirectoryInfo(dir);
            try
            {
                var subDirectories = directory.GetDirectories();
                if(subDirectories.Count() != node.Nodes.Count)
                foreach (var d in directory.GetDirectories())
                {

                    node.Nodes.Add(d.FullName, d.Name);
                }
            }
            catch (UnauthorizedAccessException)
            {
            }
        }

        private static TreeNode SelectPath(string path, TreeNode rootNode)
        {
            var x = path.Split('\\');
            var p = string.Empty;
            var n = rootNode;

            for (int i = 0; i < x.Length; i++)
            {
                var s = x[i];
                System.Diagnostics.Debug.Print(s);
                p += s + @"\";
                if (rootNode.Text.Contains(s))
                {
                    continue;
                }

                PopulateTree(n.FullPath, n);
                n = rootNode.Nodes.Find(p.Remove(p.Length - 1), true).FirstOrDefault();
                //n.Expand();
            }

            return n;
        }

        private void BgwFindTracksProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.toolStripProgressBar1.Value = e.ProgressPercentage < 98 ? e.ProgressPercentage : 0;
        }

        private void BgwFindTracksRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            dataGridView1.DataSource = e.Result;
        }

        private void FindTracks(object sender, DoWorkEventArgs eventArgs)
        {
            var args = (object[])eventArgs.Argument;
            var path = args[0].ToString();
            var searchOption = (SearchOption)args[1];
            var extensions = new List<string> { "*.MP3", "*.M4A", "*.FLAC" };
            var tracks = new List<Track>();
            var di = new DirectoryInfo(path);
            long totalProgressPerExtension = 100 / extensions.Count;

            for (var i = 0; i < extensions.Count; i++)
            {
                var extension = extensions[i];
                try
                {
                    var fileInfos = di.GetFiles(extension, searchOption);
                    var progress = ((float)totalProgressPerExtension) / fileInfos.Count();
                    float progressPerExtension = 0;

                    foreach (var fileInfo in fileInfos)
                    {
                        tracks.Add(new Track(fileInfo));
                        progressPerExtension += progress;
                        this.bgwFindTracks.ReportProgress((int)((progressPerExtension + totalProgressPerExtension) * (i + 1)));
                    }

                    this.bgwFindTracks.ReportProgress((int)totalProgressPerExtension * (i + 1));
                }
                catch (UnauthorizedAccessException)
                {
                }
            }

            eventArgs.Result = tracks;
        }

        private void Form1Load(object sender, EventArgs e)
        {
            var x = treeView1.Nodes.Add(@"C:");
            PopulateTree(@"C:\", x);
            treeView1.SelectedNode = SelectPath(ConfigurationManager.AppSettings["lastfolder"], x);
            PopulateTree(treeView1.SelectedNode.FullPath, treeView1.SelectedNode);
         }

        private void ZoekAlleOnderliggendeMuziekbestandenToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.bgwFindTracks.RunWorkerAsync(new object[] { this.treeView1.SelectedNode.FullPath, SearchOption.AllDirectories });
        }

        private void Form1FormClosing(object sender, FormClosingEventArgs e)
        {
            var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            config.AppSettings.Settings["lastfolder"].Value = treeView1.SelectedNode.FullPath;
            config.Save();
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            foreach (TreeNode node in e.Node.Nodes)
            {
                PopulateTree(node.FullPath, node);
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (!this.bgwFindTracks.IsBusy)
            {
                this.bgwFindTracks.RunWorkerAsync(new object[] { e.Node.FullPath, SearchOption.TopDirectoryOnly });
            }
        }

        private void haalCoverArtOpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            IAlbumartHelper albumartHelper = new LastFmAlbumArtHelper(ConfigurationManager.AppSettings["lastfmapikey"]);

            foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
            {
                var track = (Track)row.DataBoundItem;
                var folder = Path.GetDirectoryName(track.file.FullName);
                Image x;
                x = File.Exists(folder + @"\folder.jpg") ? Image.FromFile(folder + @"\folder.jpg") : albumartHelper.GetAlbumArtImage(track);
                if (x != null)
                    track.CoverArt = x;

            }
        }

        private void verwijderCoverArtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow selectedRow in this.dataGridView1.SelectedRows)
            {
                var track = (Track)selectedRow.DataBoundItem;
                track.CoverArt = null;
            }
        }
    }
}